package cn.lucky.thread.security;

/**
 * @Author: jianglingpeng
 * @Date: 2020/9/19
 * @Description:
 *  从四个线程买100张票的例子，引出线程安全问题
 *      从例子可以看出，四个线程同时卖一百张票，可能会出现四个线程都卖了第N张票的情况，这种情况就属于线程安全问题
 *
 *
 */
public class ThreadSecurityIssue {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        /*启动四个线程,同时卖票*/
        new Thread(ticket).start();
        new Thread(ticket).start();
        new Thread(ticket).start();
        new Thread(ticket).start();
    }
}

class Ticket implements Runnable{

    /*初始化票数*/
    private int ticketNumber = 100;

    @Override
    public void run() {
            while (ticketNumber > 0) {
                try {
                    Thread.sleep(100 );
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程[" + Thread.currentThread().getName() + "] 卖出了第" + ticketNumber + "号票");
                ticketNumber--;

            }


    }
}